package com.wenkaihu.android.chess.view;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.Paint.Style;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;

public class CoordinateView extends View {
	private Point basePoint;

	private Paint paint;

	private float baseValue = 0.0f;
	// the block item height
	public static int ITEM_HIGHT = 40;
	// the count of item in width & height
	public int xCount, yCount;

	public ArrayList<Point> pieces;

	public static int[] LOCK = new int[0];
	
	public CoordinateView(Context context, Display display) {
		super(context);

		pieces = new ArrayList<Point>();
        paint = new Paint();
        paint.setColor(Color.GREEN);

        xCount = display.getWidth() / ITEM_HIGHT;
        yCount = display.getHeight() / ITEM_HIGHT;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		paint.setColor(Color.GRAY);
		paint.setShader(null);
		paint.setStyle(Style.FILL_AND_STROKE);

		// draw the grid
		for (int i = 1; i < yCount; i++) {
			canvas.drawLine(baseValue, i * ITEM_HIGHT, xCount * ITEM_HIGHT, i * ITEM_HIGHT, paint);
		}

		for (int i = 1; i < xCount; i++) {
			canvas.drawLine(i * ITEM_HIGHT, baseValue, i * ITEM_HIGHT, yCount * ITEM_HIGHT, paint);
		}

		// draw the pieces
		synchronized (LOCK) {
			for (Point point : pieces) {
				if(pieces.indexOf(point) % 2 == 0) {
					paint.setColor(Color.WHITE);
					paint.setShader(new RadialGradient(point.x * ITEM_HIGHT + ITEM_HIGHT / 2 - 5,point.y * ITEM_HIGHT + ITEM_HIGHT / 2 - 5,ITEM_HIGHT / 2 + 1,Color.WHITE,Color.GRAY,Shader.TileMode.MIRROR));
				}else {
					paint.setColor(Color.BLACK);
					paint.setShader(new RadialGradient(point.x * ITEM_HIGHT + ITEM_HIGHT / 2 - 5,point.y * ITEM_HIGHT + ITEM_HIGHT / 2 - 5,ITEM_HIGHT / 2 + 1,Color.GRAY,Color.BLACK,Shader.TileMode.MIRROR));
				}
				canvas.drawCircle(point.x * ITEM_HIGHT + ITEM_HIGHT / 2, point.y * ITEM_HIGHT + ITEM_HIGHT / 2, ITEM_HIGHT / 2 - 1, paint);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		fillTheBlock(event.getX(), event.getY());
		return super.onTouchEvent(event);
	}

	public void fillTheBlock(float x, float y){
		addToAll((int)x / ITEM_HIGHT, (int)y / ITEM_HIGHT);
		invalidate();
	}
	
	public void addToAll(int x, int y){
		synchronized (LOCK) {
			basePoint = new Point(x, y);
			if (pieces.contains(basePoint)) {
				// pieces.remove(basePoint);
			} else {
				pieces.add(basePoint);
			}	
		}
		
	}
	
	public int getTotalSize(){
		return pieces.size();
	}
	
	public void refresh(){
		invalidate();
	}
}
